package com.itheima.health.service.impl;

import com.google.common.collect.Lists;
import com.itheima.health.common.Globalconstant;
import com.itheima.health.dao.OrderSettingDao;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.OrderSettingService;
import com.itheima.health.util.OfficeUtils;
import com.itheima.health.vo.OrderSettingVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@Slf4j
@Service
public class OrderSettingServiceImpl implements OrderSettingService {
    @Autowired
    OrderSettingDao orderSettingDao;

    @Override
    public void upload(MultipartFile excelFile) throws Exception {
        ArrayList<OrderSetting> orderLists = parseOffice(excelFile);
        //操作数据库
        Lists.partition(orderLists,500).stream().
                forEach(orderList-> orderSettingDao.add(orderList)
                    );

    }

    ///**
    // * 石恆斌
    // * @param orderSetting
    // */
    //@Override
    //public void editNumberByDate(OrderSetting orderSetting) {
    //    int count = orderSettingDao.findCountByOrderDate(orderSetting);
    //    if (count > 0) {
    //        orderSettingDao.editNumberByOrderDate(orderSetting);
    //    } else {
    //        orderSettingDao.add(orderSetting);
    //    }
    //}

    @Override
    public List<Map> getOrderSettingByMonth(int year, int month) {
        //获取 日历 对象
        Calendar calendar = Calendar.getInstance() ;
        //填充年
        calendar.set(Calendar.YEAR , year);
        //填充月 calenda里的月份是0-11
        calendar.set(Calendar.MONTH , month - 1);
        //获取2020-02日历的最大字段，也就是最大多少天
        int maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        //填充 最后一天
        calendar.set(Calendar.DAY_OF_MONTH , maxDay);

        Calendar calendarStart = Calendar.getInstance() ;
        calendarStart.set(year, month-1,1);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String start = sdf.format(calendarStart.getTime());
        String end = sdf.format(calendar.getTime());
        System.out.println("start = " + start);
        System.out.println("end = " + end);
        List<OrderSetting> orderSettingByMonth = orderSettingDao.getOrderSettingByMonth(start, end);
        List<Map> list = new ArrayList<>();
        for (OrderSetting orderSetting : orderSettingByMonth) {
            HashMap hashMap = new HashMap();
            hashMap.put("date", orderSetting.getOrderDate().getDate());
            hashMap.put("number", orderSetting.getNumber());
            hashMap.put("reservations", orderSetting.getReservations());
            list.add(hashMap);
        }
        return list;
    }

    @Override
    public List<OrderSettingVO> getOrderSettingByMonth(Integer year, Integer month) {
        //orderDate like "2019-03%"
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Globalconstant.EXCEL_DATA_PATTERN);
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR,year);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        Date beginTime1 = calendar.getTime();
        String beginTime = simpleDateFormat.format(beginTime1);
        calendar.add(Calendar.MONTH,1);
        calendar.add(Calendar.DATE,-1);
        Date endTime1 = calendar.getTime();
        String endTime = simpleDateFormat.format(endTime1);

        List<OrderSetting> orderSettingByMonth = orderSettingDao.getOrderSettingByMonth(beginTime, endTime);
        List<OrderSettingVO> list = orderSettingByMonth.stream().map(OrderSetting -> {
            OrderSettingVO orderSettingVO = new OrderSettingVO();
            BeanUtils.copyProperties(OrderSetting, orderSettingVO);
            Date orderDate = OrderSetting.getOrderDate();
            calendar.setTime(orderDate);
            int date = calendar.get(Calendar.DATE);
            orderSettingVO.setDate(date);
            return orderSettingVO;
        }).collect(Collectors.toList());
        return list;
    }

    @Override
    public void editNumberByDate(OrderSetting orderSetting) {
        //判断是否存在
        int count  = orderSettingDao.getCount(orderSetting);
        if (count == 0) {
            orderSettingDao.insert(orderSetting);
        }

        //查看预约的数量,不能被已预约数量少
        Integer Reservations = orderSettingDao.getReservationsByOrderDate(orderSetting);
        if (Reservations > orderSetting.getNumber()){
            throw new BusinessRuntimeException("修改的预约数太少了.不能比已预约人数少");
        }
        //修改数据库
        orderSettingDao.updateNumberByOrderDate(orderSetting);
    }

    public ArrayList<OrderSetting> parseOffice(MultipartFile excelFile) throws Exception {
        //解析excel表格
        ArrayList<OrderSetting> resultList = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat(Globalconstant.EXCEL_DATA_PATTERN);
        //正确的文件类型 自动判断2003或者2007
        Workbook workbook = OfficeUtils.getWorkbookAuto(excelFile);
        Sheet sheet = workbook.getSheetAt(0);//默认只有一个sheet
        int rows = sheet.getPhysicalNumberOfRows();//获得sheet有多少行
        //读第一个sheet
        for (int i = 1; i < rows; i++) {
            Row row = sheet.getRow(i);
            if (row.getCell(0) != null && row.getCell(1) != null) {
                OrderSetting orderSetting = new OrderSetting();
                orderSetting.setOrderDate(sdf.parse(row.getCell(0).toString()));
                orderSetting.setNumber((int)row.getCell(1).getNumericCellValue());
                resultList.add(orderSetting);
            }
        }
        log.info("resultList={}",resultList);
        return resultList;
    }
}